package kamikaze.service.product;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kamikaze.bean.Product;
import kamikaze.service.ErrorHandler;
import kamikaze.utils.Database;
import kamikaze.utils.Database.Template;

public class UpdateProductServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2964419447328782083L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		new ErrorHandler(Arrays.asList("Method is not supported")).handle(req, resp);
	}

	@Override
	protected void doPost(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {

		final String id = req.getParameter("id");
		if (id != null && !id.isEmpty()) {

			try {

				Product product = (Product) Database.get().execute(
						new Template<Object>() {

							@Override
							public Object query(EntityManager em) throws ServletException, IOException {

								Query q = em
										.createQuery("Select p from Product p where p.productId= :productId and deleted=false");
								q.setParameter("productId", Long.valueOf(id));
								Product product = (Product) q.getSingleResult();
								product.setCategory(req.getParameter("prodCat"));
								product.setName(req.getParameter("prodName"));
								product.setPicture(req
										.getParameter("prodPicture"));

								BigDecimal price = BigDecimal.ZERO;
								String strPrice = req.getParameter("prodPrice");
								if (strPrice != null) {
									strPrice = strPrice.replaceAll(",", "");
									Double dprice = Double
											.parseDouble(strPrice);
									price = BigDecimal.valueOf(dprice);
								}
								product.setPrice(price);
								product.setComment(req
										.getParameter("sellerComment"));
								
								List<String> errors = product.validate();
								if (!errors.isEmpty()) {
									new ErrorHandler(errors).handle(req, resp);
								} else {
									em.persist(product);
								}

								return product;
							}
						});

				resp.sendRedirect("/retrieveProduct");

			} catch (Exception ex) {
				new ErrorHandler(Arrays.asList(ex.getMessage())).handle(req,
						resp);
				return;
			}

		} else {
			ErrorHandler errorHandler = new ErrorHandler();
			errorHandler.addErrorMessageIfNotNull("Product ID is unknown");
			errorHandler.handle(req, resp);
			return;
		}
	}

}
